package com.mxx.common.flow;

import com.mxx.common.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author: mxx
 * @date: 2021/12/31
 * @time: 11:30
 * @Description: 描述信息
 */
@Slf4j
public class DefaultFlowManager extends AbstractFlowManager<DefaultFlowManager> {

    public DefaultFlowManager() {
    }

    public DefaultFlowManager(Map<String, FlowModule> moduleMap) {
        super(moduleMap);
    }

    @Override
    public void async(FlowEvent event, Map<String, Object> attr) {

    }

    @Override
    public void sync(FlowEvent event, Map<String, Object> attr) {
        String eventName = event.eventName();
        FlowModule flowModule = this.moduleMap.get(eventName);
        FlowContext context = new FlowContext(event, attr);

        String tradId = RandomUtil.randomOrderNo("T");
        context.setTradId(tradId);

        if (flowModule != null) {
            Flows flows = flowModule.newFlows();
            log.info("[{}] flows : {} ", tradId, flows.getNameLine());
            try {
                super.init(flows, context);
                log.info("flows init success");
                super.execute(flows, context);
                log.info("flows execute success");
                super.complete(flows, context);
                log.info("[{}] flows : run successful", tradId);
            } catch (FlowException ex) {
                log.error("[{}] exception : flow:{}, method:{}, msg : {}  ", tradId, ex.flow().flowName(), ex.getMethodName(), ex.getMessage());
                super.canException(flows, context, ex);
            }
        }
    }
}
